import React, { useState, useEffect } from "react";
import { Input, Button, Table, Select, Modal, Form, Radio, Upload } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import { SearchOutlined, RedoOutlined } from "@ant-design/icons";
import systemStyle from "./index.module.scss";
import { userColumn } from "./column";
import { queryUserList } from "@/api/auth.js";
import Blupload from "../../components/Blupload";
import { modifyUserById } from "@/api/auth.js";

export default function User() {
  const [form] = Form.useForm();
  const [paginationObj, setPaginationObj] = useState({ page: 1, size: 10 });
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);
  const [editDialog, setEditVisible] = useState(false);
  const [titleImg, setTitleImg] = useState("");
  const [modifyId, setModifyId] = useState(-1);
  const [searchObj, setSearchObj] = useState({
    loginType: null,
    nickname: null,
  });
  const nav = useNavigate();
  const location = useLocation();
  const requireRule = { required: true, message: "必填字段" };

  useEffect(() => {
    getList();
  }, []);

  const getList = async (requestObj = {}) => {
    const res = await queryUserList(requestObj);
    console.log("dictlist", res);
    setList(res.data);
  };

  const handlePageChange = (page, size) => {
    // getList({ page, size });
  };

  const handleSizeChange = (page, size) => {
    // getList({ page, size });
  };

  const handleToData = (id) => {
    console.log("跳转id", id, location);
    nav(`/site/dictData?dictId=${id}`, {
      state: { originPath: location.pathname },
    });
  };
  //修改nickname
  const handleDictName = (e) => {
    setSearchObj((preState) => {
      return { ...preState, nickname: e.target.value };
    });
  };
  // 修改登录类型
  const handleChangeLoginType = (value) => {
    setSearchObj((preState) => {
      return { ...preState, loginType: value };
    });
  };

  // 重置
  const handleResetSearch = () => {
    setSearchObj({
      loginType: null,
      nickname: null,
    });
  };
  // 查询
  const handleSearch = () => {
    getList(searchObj);
    handleResetSearch();
  };

  const openEditDialog = (row) => {
    const { username, nickname, status, roleId } = row;
    console.log(row, "row");
    setTitleImg(row.avatar);
    setModifyId(row.id);
    form.setFieldsValue({
      username,
      nickname,
      status,
      roleId,
    });

    setEditVisible(true);
  };

  const handleCancelDialog = () => {
    form.resetFields();
    setModifyId(-1);
    setEditVisible(false);
    setTitleImg("");
  };

  // 自定义处理上传

  const handleUploadChange = (titleImg) => {
    if (titleImg != "delete") {
      console.log(titleImg, "title");
      setTitleImg(titleImg);
    } else {
      setTitleImg("");
    }
  };
  // 表单提交

  // 表单是否提交

  const handleFinishFail = (err) => {
    console.log("formerr", err);
  };
  const handleFinish = async (value) => {
    const requestObj = value;
    requestObj.id = modifyId;
    if(titleImg) {
      requestObj.titleImg = titleImg;
    }
    console.log(requestObj, "obj");
    const res = await modifyUserById(requestObj);
    console.log("修改", res);
    window.$message.success("修改成功!");
    getList();
    setEditVisible(false);
  };

  const columns = userColumn({ openEditDialog });
  return (
    <div className={systemStyle.index}>
      <div className={systemStyle.top}>
        <div className={systemStyle.search}>
          <h3>用户名称:</h3>
          <Input
            placeholder="请输入标签名称"
            value={searchObj.nickname}
            onChange={handleDictName}
            style={{ width: "200px", marginRight: "10px" }}
          />
          <h3>登录方式:</h3>
          <Select
            value={searchObj.loginType}
            style={{ width: "200px", marginRight: "10px" }}
            onChange={handleChangeLoginType}
            options={[
              {
                label: "账号",
                value: 1,
              },
              {
                label: "gitee码云",
                value: 2,
              },
              {
                label: "github",
                value: 3,
              },
              {
                label: "qq",
                value: 4,
              },
              {
                label: "微博",
                value: 5,
              },
            ]}
          ></Select>
          <Button
            icon={<SearchOutlined />}
            type="primary"
            className={systemStyle["ant-btn"]}
            onClick={handleSearch}
          >
            查找
          </Button>
          <Button
            icon={<RedoOutlined />}
            className={systemStyle["ant-btn"]}
            onClick={handleResetSearch}
          >
            重置
          </Button>
        </div>
      </div>
      <div className={systemStyle["table-container"]}>
        <Table
          columns={columns}
          dataSource={list}
          rowKey={(record) => record.id}
          loading={loading}
          pagination={{
            pageSize: paginationObj.pageSize,
            current: paginationObj.currentPage,
            pageSizeOptions: [3, 5, 10, 20],
            showSizeChanger: true,
            total: paginationObj.total,
            showTotal: (total) => `共${total}条`,
            onChange: handlePageChange,
            onShowSizeChange: handleSizeChange,
          }}
        />
      </div>
      <Modal
        open={editDialog}
        onCancel={handleCancelDialog}
        title="修改用户"
        footer={false}
      >
        <Form
          style={{ padding: "20px" }}
          form={form}
          onFinishFailed={handleFinishFail}
          onFinish={handleFinish}
        >
          <Form.Item label="头像">
            <Blupload
              handleUploadChange={handleUploadChange}
              titleImg={titleImg}
            />
          </Form.Item>
          <Form.Item label="用户名" name="username" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>
          <Form.Item label="昵称" name="nickname" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>
          <Form.Item label="状态" name="status" rules={[requireRule]}>
            <Radio.Group name="radiogroup">
              <Radio value={1}>禁用</Radio>
              <Radio value={2}>正常</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="角色" name="roleId" rules={[requireRule]}>
            <Radio.Group name="radiogroup2">
              <Radio value={1}>超级管理员</Radio>
              <Radio value={2}>管理员</Radio>
              <Radio value={3}>演示</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item style={{ textAlign: "center" }}>
            <Button
              onClick={handleCancelDialog}
              style={{ marginRight: "40px" }}
            >
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
